//
//  YJLoginViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/11/22.
//  Copyright © 2017年 史宵宵. All rights reserved.
//

#import "YJLoginViewController.h"
#import "loginTextField.h"
#import "YJSelectionIdentityViewController.h"

#define KTEXTFIELDTAG  1000
@interface YJLoginViewController ()<UITextFieldDelegate>
@property (nonatomic,assign) NSInteger selectIndex;
@property (nonatomic,strong) NSMutableArray *textArray;//显示内容
@property (nonatomic,strong) NSMutableArray *imgArray;//显示图片

@property (nonatomic,copy) NSString *identifyingCode; //获取的验证码
@property (nonatomic,strong) NSMutableArray *textFieldValueArray;//输入框的值
@property(nonatomic,strong)NSTimer *timer;
@property (nonatomic,weak) UIButton *cerButton;//获取验证码

@end

@implementation YJLoginViewController
- (NSMutableArray *)textFieldValueArray{
    if (!_textFieldValueArray) {
        _textFieldValueArray = [NSMutableArray array];
    }
    return _textFieldValueArray;
}
- (NSMutableArray *)textArray{
    if (!_textArray) {
        _textArray = [NSMutableArray array];
    }
    return _textArray;
}
- (NSMutableArray *)imgArray{
    if (!_imgArray) {
        _imgArray = [NSMutableArray array];
    }
    return _imgArray;
}
//- (UIStatusBarStyle)preferredStatusBarStyle{
//    
//    return UIStatusBarStyleLightContent;
//    
//}
- (instancetype)initWithSelectIndex:(NSInteger)index{
    self = [super init];
    if (self) {
        self.selectIndex = index;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
//    [Global setStatusBarBackgroundColor:[UIColor clearColor]];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.frame = CGRectMake(0, -20, kScreenW, kScreenH+20);
    self.textFieldValueArray  = [NSMutableArray arrayWithObjects:@"",@"",@"",@"", nil];
    if (self.loginType == KLoginUser) {
        self.textArray = [NSMutableArray arrayWithArray:@[@"输入您的手机号或系统注册码",@"输入您的密码"]];
        self.imgArray = [NSMutableArray arrayWithArray:@[@"Login_phone",@"Login_Secret"]];
    }else if (self.loginType == KBackPassWordTelCer) {
        self.textArray = [NSMutableArray arrayWithArray:@[@"输入您的手机号",@"验证码",@"输入您的新密码",@"请再次输入新密码"]];
        self.imgArray = [NSMutableArray arrayWithArray:@[@"Login_phone",@"Login_phone",@"Login_Cer",@"Login_Secret",@"Login_Secret"]];
    }
    
    if (self.loginType == KLoginUser) {
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenH - 60.5, kScreenW, 0.5)];
        lineView.backgroundColor = KTEXTBLACKCOLOR;
        [self.view addSubview:lineView];
        
        UIView *sepView = [[UIView alloc]initWithFrame:CGRectMake(kScreenW / 2- 0.5, kScreenH - 60, 0.5, 60)];
        sepView.backgroundColor = KTEXTBLACKCOLOR;
        [self.view addSubview:sepView];
        
        NSArray *array = @[@"忘记密码",@"注册账号"];
        for (int i = 0; i < 2; i ++) {
            UIButton *registerButton = [[UIButton alloc]init];
            registerButton.frame = CGRectMake( kScreenW / 2 * i,kScreenH - 60, kScreenW / 2, 60);
            [registerButton setTitle:array[i] forState:UIControlStateNormal];
            [registerButton setTitleColor:KTEXTBLACKCOLOR forState:UIControlStateNormal];
            registerButton.tag = 2000 + i;
            [registerButton addTarget:self action:@selector(registerOrForget:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:registerButton];
        }
    }
}
#pragma mark - 忘记密码/注册账号
- (void)registerOrForget:(UIButton *)sender{
    
    if (sender.tag - 2000 == 1) {
        YJSelectionIdentityViewController *selectionIdentityVC = [[YJSelectionIdentityViewController alloc]init];
        [self.navigationController pushViewController:selectionIdentityVC animated:YES];
    }else{
        //个人编辑页面
        YJLoginViewController *loginVC = [[YJLoginViewController alloc]init];
        loginVC.loginType = KBackPassWordTelCer;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIButton *backButton = [[UIButton alloc]init];
    backButton.frame = CGRectMake(0, 20, 50, 50);
    [backButton setImage:[UIImage imageNamed:@"black_back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:backButton];
    
    UIImageView *logoImageView = [[UIImageView alloc]init];
    logoImageView.frame = CGRectMake(kScreenW / 3, kScreenH / 7, kScreenW / 3 , kScreenW /3 );
    logoImageView.contentMode = UIViewContentModeScaleAspectFill;
    logoImageView.image = [UIImage imageNamed:@"Login_sign"];
    [cell.contentView addSubview:logoImageView];
    
    for (int i = 0; i < self.textArray.count; i ++) {
        
        loginTextField *loginTF = [[loginTextField alloc]initWithFrame:CGRectMake(20, kScreenH / 5 + kScreenW / 2/ 3 + 30 + 50 *i, kScreenW - 40 , 40) placeholder:self.textArray[i] imageStr:self.imgArray[i]];
        loginTF.delegate = self;
        loginTF.tag = KTEXTFIELDTAG + i;
        [cell.contentView  addSubview:loginTF];
        if (self.loginType == KBackPassWordTelCer && (i == 0 || i == 1)) {
            loginTF.keyboardType = UIKeyboardTypePhonePad;
        }
        if (self.loginType == KLoginUser && i == 1) {
            loginTF.secureTextEntry = YES;
        }
        if (self.loginType == KBackPassWordTelCer && i == 1) {
            UIButton *cerButton = [[UIButton alloc]init];
            cerButton.frame = CGRectMake(CGRectGetMaxX(loginTF.frame) - 85, CGRectGetMinY(loginTF.frame) + 5, 80, 30);
            cerButton.backgroundColor = KBACKNAVIGATIONCOLOR;
            [cerButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            [cerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            cerButton.titleLabel.font = [UIFont systemFontOfSize:12];
            cerButton.userInteractionEnabled = YES;
            cerButton.layer.cornerRadius = 2;
            [cerButton addTarget:self action:@selector(getIdentifyingCode) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:cerButton];
            self.cerButton = cerButton;
        }
    }
    //确定
    NSString *str;
    if (self.loginType == KLoginUser) {
        str = @"登录";
    }else{
        str = @"确定";
    }
    CompleteButton *loginButton = [[CompleteButton alloc]initWithFrame:CGRectMake(20, kScreenH / 5 + kScreenW / 2/ 3 + 30 + 50 * (self.loginType == KLoginUser?2:4) + 10, kScreenW - 40, 40) bgColor:KBACKNAVIGATIONCOLOR tColor:[UIColor whiteColor] text:str];
    [loginButton addTarget:self action:@selector(roleLogin) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:loginButton];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kScreenH;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    MyLog(@"%@",self.textFieldValueArray);
    MyLog(@"%@",self.textFieldValueArray[0]);
    [self.textFieldValueArray replaceObjectAtIndex:textField.tag - KTEXTFIELDTAG withObject:textField.text];
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [textField resignFirstResponder];
}

#pragma mark - 获取验证码
- (void)getIdentifyingCode{
    [self.tableView endEditing:YES];
    if (strIsEmpty(self.textFieldValueArray[0])) {
        [Global showActivityWithView:self.view withText:@"请输入手机号"];
        return;
    }
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:self.textFieldValueArray[0] forKey:@"phone"];   //手机号
    [yjNetWorkManger requestType:GET andURL:[JSPathUtil urlAppGetCode] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
//            NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:response];
//            self.identifyingCode = dic[@"code"];
        }
    }];
    self.cerButton.userInteractionEnabled=NO;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
}
static int count=30;

-(void)handleTimer:(NSTimer *)_timer
{
    //在这里进行处理
    count--;
    if (count==0)
    {
        self.cerButton.userInteractionEnabled=YES;
        [self.cerButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        count=30;
        [self.timer invalidate];
    }
    else
    {
        self.cerButton.userInteractionEnabled=NO;
        [self.cerButton setTitle:[NSString stringWithFormat:@"%ds重新获取",count] forState:UIControlStateNormal];
    }
}

#pragma mark - 登录
- (void)roleLogin{
    [self.tableView endEditing:YES];
    if (strIsEmpty(self.textFieldValueArray[0])) {
        [Global showActivityWithView:self.view withText:[NSString stringWithFormat:@"请输入%@",self.textArray[0]]];
        return;
    }
    if (strIsEmpty(self.textFieldValueArray[1])) {
        [Global showActivityWithView:self.view withText:[NSString stringWithFormat:@"请输入%@",self.textArray[1]]];
        return;
    }
    if (self.loginType != KLoginUser && strIsEmpty(self.textFieldValueArray[2])) {
        [Global showActivityWithView:self.view withText:[NSString stringWithFormat:@"请输入%@",self.textArray[2]]];
        return;
    }
    if (self.loginType != KLoginUser && strIsEmpty(self.textFieldValueArray[3])) {
        [Global showActivityWithView:self.view withText:[NSString stringWithFormat:@"请输入%@",self.textArray[3]]];
        return;
    }
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    NSString *url;
    if (self.loginType == KLoginUser) {
        url = [JSPathUtil urlAppApiOauth]; //登录
        [dic setValue:self.textFieldValueArray[0] forKey:@"username"];   //系统码或者手机号
        [dic setValue:self.textFieldValueArray[1] forKey:@"password"];   //密码
    }else{
        url = [JSPathUtil urlAppApiChangePassword]; //确定新密码
        [dic setValue:self.textFieldValueArray[0] forKey:@"phone"];   //手机号
        [dic setValue:self.textFieldValueArray[1] forKey:@"code"];   //验证码
        [dic setValue:self.textFieldValueArray[2] forKey:@"password"];   //密码
        [dic setValue:self.textFieldValueArray[3] forKey:@"repassword"];   //确认密码
    }
    [yjNetWorkManger requestType:POST andURL:url andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            if (self.loginType == KLoginUser) {
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:response];
                [Global setUserTokenInfo:dic[@"token"]]; //
                [JHUserInfo saveUserInfo:dic[@"userInfo"]];
                [Global showActivityWithView:self.view withText:@"登录成功"];
                [[Global appdelegete] enterTheMainViewIndex:self.selectIndex];
            }else{
                [Global showActivityWithView:self.view withText:@"修改密码成功"];
                YJLoginViewController *loginVC = [[YJLoginViewController alloc]init];
                loginVC.loginType = KLoginUser;
                [self.navigationController pushViewController:loginVC animated:YES];
            }
        }
    }];
}
#define mark - 返回
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
